package cn.net.zhenchan.utils;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

	public static String isDisabledString(int isDisabled){
		String result = "";
		switch (isDisabled) {
		case 0:
			result = "可用";
			break;
		case 1:
			result = "禁用";
			break;
		default:
			result = "其他";
			break;
		}		return result;
	}
	
	public static String isAffix(int isAffix){
		String result = "";
		switch (isAffix) {
		case 0:
			result = "允许";
			break;
		case 1:
			result = "不允许";
			break;
		default:
			result = "其他";
			break;
		}
		return result;
	}
	public static String allowReply(int allowReply){
		String result = "";
		switch (allowReply) {
		case 0:
			result = "允许";
			break;
		case 1:
			result = "不允许";
			break;
		default:
			result = "其他";
			break;
		}
		return result;
	}
	public static String category(int category){
		String result = "";
		switch (category) {
		case 0:
			result = "普通帖";
			break;
		case 1:
			result = "投票貼";
			break;
		case 2:
			result = "精華帖";
			break;
		case 3:
			result = "熱門貼";
			break;
		case 4:
			result = "置頂帖";
			break;
		case 5:
			result = "公告貼";
			break;
		default:
			result = "其他帖";
			break;
		}
		return result;
	}
	
	public static String isAdmin(int isAdmin){
		String result = "";
		switch (isAdmin) {
		case 0:
			result = "否";
			break;
		case 1:
			result = "是";
			break;
		default:
			result = "其他";
			break;
		}
		return result;
	}
	
	public static String prohibitPost(Integer prohibitPost){
		String result = "";
		switch (prohibitPost) {
		case 0:
			result = "不禁言";
			break;
		case 1:
			result = "永久禁言";
			break;
		case 2:
			result = "定期禁言";
			break;
		default:
			result = "其他";
			break;
		}
		return result;
	}
	/**
	 * 获取注册ip
	 * @param request
	 * @return
	 */
	public static String getRemortIP(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
	    if ((!StringUtils.isBlank(ip)) && (!"unknown".equalsIgnoreCase(ip))) {
	      return ip;
	    }
	    ip = request.getHeader("X-Forwarded-For");
	    if ((!StringUtils.isBlank(ip)) && (!"unknown".equalsIgnoreCase(ip)))
	    {
	      int index = ip.indexOf(',');
	      if (index != -1) {
	        return ip.substring(0, index);
	      }
	      return ip;
	    }

	    return request.getRemoteAddr();
	}
	/** 
     * 获取当前网络ip 
     * @param request 
     * @return 
     */  
    public static String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }
	public static boolean validateUserName(String userName){
		String regEx = "[a-zA-Z]{1}[a-zA-Z0-9_]{1,15}";
		Pattern pattern = Pattern.compile(regEx);
		Matcher m = pattern.matcher(userName);
		boolean rs = m.matches();
		return rs;
	}
	public static boolean validateMobile(String mobile){
		// 要验证的字符串
	    // 邮箱验证规则
	    String regEx = "^1[3|4|5|8][0-9]\\d{8}$";
	    // 编译正则表达式
	    Pattern pattern = Pattern.compile(regEx);
	    // 忽略大小写的写法
	    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
	    Matcher matcher = pattern.matcher(mobile);
	    // 字符串是否与正则表达式相匹配
	    boolean rs = matcher.matches();
	    
	    return rs;
	}
	public static boolean validateEmail(String email){
		// 要验证的字符串
	    // 邮箱验证规则
	    //String regEx = "[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
		String regEx = "\\w+(\\.\\w)*@\\w+(\\.\\w{2,3}){1,3}";
	    // 编译正则表达式
	    Pattern pattern = Pattern.compile(regEx);
	    // 忽略大小写的写法
	    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
	    Matcher matcher = pattern.matcher(email);
	    // 字符串是否与正则表达式相匹配
	    boolean rs = matcher.matches();
	    
	    return rs;
	}
	public static boolean validateUrl(String url){
		// 要验证的字符串
	    // 邮箱验证规则
	    String regEx = "^((http|https)://)?([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$";
	    // 编译正则表达式
	    Pattern pattern = Pattern.compile(regEx);
	    // 忽略大小写的写法
	    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
	    Matcher matcher = pattern.matcher(url);
	    // 字符串是否与正则表达式相匹配
	    boolean rs = matcher.matches();
	    
	    return rs;
	}
	
	public static String encoder(String str) throws UnsupportedEncodingException{
		return URLEncoder.encode(str, "UTF-8");
	}
	public static String decoder(String str) throws UnsupportedEncodingException{
		return URLDecoder.decode(str, "UTF-8");
	}
	
	public static String generateHtmlTemplate(HttpServletRequest request, String name, String info, List<String> photos, String torrent) throws Exception{
		
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("<div class=\"padding-bottom:1em\"><style type=\"text/css\">.pcb{margin-right:0}</style><div class=\"pcb\">");
		buffer.append("<div class=\"min-height: 100px;\">");
		buffer.append("<table cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td class=\"font-size: 14px;\" id=\"postmessage_1849988\">");
		buffer.append("<br><strong><font color=\"green\"><br>");
		buffer.append("<font color=\"green\"><br>");
		buffer.append(info);
		buffer.append("<br>");
		if(photos != null && photos.size() > 0){
			for(int i = 0;i<photos.size();i++){
				buffer.append("<img id=\"aimg_"+i+"\" onclick=\"zoom(this, this.src, 0, 0, 0)\" class=\"zoom\" src=\""+photos.get(i)+"\" onmouseover=\"img_onmouseoverfunc(this)\" onload=\"thumbImg(this)\" alt=\"\" border=\"0\"><br>");
			}
		}
		buffer.append("<br>");
		buffer.append("<font color=\"red\"><font color=\"red\"><font color=\"red\"><br>");
		buffer.append("<strong><br>");
		buffer.append("<font color=\"red\">BT種子：</font>");
		buffer.append("<span style=\"white-space: nowrap\" id=\"attach_218361\">");
		buffer.append("<a href=\""+PropertyConfig.getProperty("domainUrl")+"/bbsweb/bbs/download/" + downloadTorrentUrl(torrent) + "\" target=\"_blank\">" + name + ".torrent.torrent</a>");
		buffer.append("</span>");
		buffer.append("</strong></font></font></font></font></td></tr></tbody></table>");
		buffer.append("</div>");
		buffer.append("</div>");
		buffer.append("</div>");
		
		return buffer.toString();
	}
	public static String generateCameraHtmlTemplate(HttpServletRequest request, String name, List<String> photos, String originUrl) throws Exception{
		
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("<div class=\"padding-bottom:1em\"><style type=\"text/css\">.pcb{margin-right:0}</style><div class=\"pcb\">");
		buffer.append("<div class=\"min-height: 100px;\">");
		buffer.append("<table cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td class=\"font-size: 14px;\" id=\"postmessage_1849988\">");
		buffer.append("<br><strong><font color=\"green\"><br/>");
		buffer.append("<font color=\"green\">"+name+"</font><br/>");
		if(photos != null && photos.size() > 0){
			for(int i = 0;i<photos.size();i++){
				buffer.append("<img id=\"aimg_"+i+"\" onclick=\"zoom(this, this.src, 0, 0, 0)\" class=\"zoom\" src=\""+photos.get(i)+"\" onmouseover=\"img_onmouseoverfunc(this)\" onload=\"thumbImg(this)\" alt=\"\" border=\"0\"/><br/>");
			}
		}
		buffer.append("<br/>");
		buffer.append("<font color=\"red\"><font color=\"red\"><font color=\"red\"><br/>");
		buffer.append("<strong><br/>");
		buffer.append("<span style=\"display:none;\" id=\"attach_218361\">");
		buffer.append("<a href=\""+ originUrl + "\" target=\"_blank\">" + originUrl + "</a>");
		buffer.append("</span>");
		buffer.append("</strong></font></font></font></font></td></tr></tbody></table>");
		buffer.append("</div>");
		buffer.append("</div>");
		buffer.append("</div>");
		
		return buffer.toString();
	}
	
	public static String downloadTorrentUrl(String torrentUrl) throws IOException{
		String result = null;
		//String torrentUrl = "http://bbs.sex169.xyz/forum.php?mod=attachment&aid=MjE2NTcwfGY0NWY1ZjQwfDE0OTcwOTAwNTJ8MHwxNTUzMzg%3D";
		torrentUrl = torrentUrl.substring(torrentUrl.lastIndexOf("=") + 1, torrentUrl.length());
		System.out.println("------------->" + torrentUrl);
		torrentUrl = torrentUrl.replace("%3D", "=");
		
		String realContent = new String(new sun.misc.BASE64Decoder().decodeBuffer(torrentUrl));
		
		String[] contents = realContent.split("\\|");
        if (contents.length < 1) {
            return null;
        }
        result = AESUtils.aes_encrypt(System.currentTimeMillis()+ "~" + contents[0], AESUtils.STR_KEY);
        
        return result;
	}
	
	public static void main(String[] args) throws Exception{
		
		System.out.println(validateUserName("d_d1111"));
		System.out.println(validateEmail("ddaadfasdf@123.com"));
		
		String format = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		int random = new Random().nextInt(100000);
		
		String result = "dddddddddddddddd"
				+ "dddddddd";
		
		System.out.println(Long.valueOf(format+random));
		
		String url = "Mjg2Mjc1fDVkMjBkMjFlfDE0OTc1ODM0MjB8MHwyMjkxMjU%3D";
		url = url.replace("%3D", "=");
		//String end = url.substring(url.lastIndexOf("d=") + 2);
		try{
			String realContent = new String(new sun.misc.BASE64Decoder().decodeBuffer(url));
	        String[] contents = realContent.split("\\|");
	        if (contents.length < 2) {
	            //return null;
	        }
	        String path = "/media/zhanglin/data/torrents/" + contents[0] + contents[1] + ".torrent";
	        
	        System.out.println(contents[0] + contents[1] + ".torrent");
	        
//	        byte[] b = null;
//	        String result2 = null;
//	        if (end != null) {
//	            BASE64Decoder decoder = new BASE64Decoder();
//	            try {
//	                b = decoder.decodeBuffer(end);
//	                result2 = new String(b, "iso-8859-1");
//	            } catch (Exception e) {
//	                e.printStackTrace();
//	            }
//	        }
//	        System.out.println(result2);
	        

		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		System.out.println(validateEmail("403937147@qq.com"));
		
	}
	
	
	
}
